package middleware

import (
	"errors"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/di"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/base/tenant"
	"github.com/gin-gonic/gin"
)

func ProfitCheck(code string) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 查看是否有权益
		// 远程调用鉴权获取用户信息
		c := di.InjectInstance()
		err := c.Invoke(func(tenantService tenant.TenantServiceIface) error {
			profits, err := tenantService.Profit(ctx)
			if err != nil {
				return err
			}
			for _, profit := range profits {
				if profit == code {
					return nil
				}
			}
			return errors.New("没有找到该模块的权益")
		})

		if err != nil {
			var errCode int
			var errMsg string
			switch code {
			case constants.ProfitAIOutbound:
				errCode = errcode.OutboundHasNoProfitError
				errMsg = "贵司未购买AI外呼，请联系客户经理开通"
			default:
				errCode = errcode.COMMON_NO_PERMISSION
				errMsg = err.Error()
			}
			response(ctx, errCode, errMsg)
			return
		}

		ctx.Next()
	}
}
